package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.ApArticleConfigService;
import com.heima.common.constants.message.WmNewsMessageConstants;
import com.heima.model.article.pojos.ApArticleConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

@Component
public class ArticleIsDownListener {

    @Autowired
    private ApArticleConfigService apArticleConfigService;

    @KafkaListener(topics = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC)
    public void recevieMessage(ConsumerRecord<?,?> record){
        Optional<? extends ConsumerRecord<?, ?>> optional = Optional.ofNullable(record);
        if(optional.isPresent()){

            //获取参数
            Object value =  record.value();

            //将json转换成map
            Map map = JSON.parseObject(value.toString(), Map.class);

            //获取参数
            Integer enable = (Integer) map.get("enable");
            Long articleId = (Long) map.get("articleId");

            //修改数据
            LambdaUpdateWrapper<ApArticleConfig> update = Wrappers.lambdaUpdate();
            update.eq(ApArticleConfig::getArticleId, articleId);

            //判断是上架还是下架
            update.set(ApArticleConfig::getIsDown, enable != 1);
            apArticleConfigService.update(update);
        }

    }
}